<template>
  <div class="assess-list-container">
    <!-- 顶部操作区 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd">+ 添加</el-button>
      <div class="filters">
        <el-select v-model="filterOrg" placeholder="组织结构" clearable class="filter-item">
          <el-option label="博才学校" value="博才学校"/>
          <el-option label="实验小学" value="实验小学"/>
          <el-option label="育才中学" value="育才中学"/>
        </el-select>
        <el-input v-model="filterName" placeholder="请输入姓名" clearable class="filter-item"/>
        <el-input v-model="filterAccount" placeholder="请输入账号" clearable class="filter-item"/>
        <el-input v-model="filterAssessor" placeholder="请输入评估人" clearable class="filter-item"/>
        <div class="filter-actions">
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="primary" @click="handleRefresh">刷新</el-button>
        </div>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-box">
      <el-table :data="currentPageTableData" style="width:100%" height="400" :header-cell-style="{ 'background-color': '#f5f7fa' }">
        <el-table-column prop="assessTime" min-width="150">
          <template #header>
            <span @click="sortTable('assessTime')" class="sortable-header">评估时间
              <span class="sort-icons">
                <i class="arrow up" :class="{active: sortField==='assessTime' && sortOrder==='asc'}"></i>
                <i class="arrow down" :class="{active: sortField==='assessTime' && sortOrder==='desc'}"></i>
              </span>
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="姓名" min-width="120"/>
        <el-table-column prop="account" label="账号" min-width="120"/>
        <el-table-column prop="org" label="组织结构" min-width="260"/>
        <el-table-column prop="assessor" label="评估人" min-width="120"/>
        <el-table-column prop="lastUpdate" label="最后修改时间" min-width="200">
          <template #header>
            <span @click="sortTable('lastUpdate')" class="sortable-header">最后修改时间
              <span class="sort-icons">
                <i class="arrow up" :class="{active: sortField==='lastUpdate' && sortOrder==='asc'}"></i>
                <i class="arrow down" :class="{active: sortField==='lastUpdate' && sortOrder==='desc'}"></i>
              </span>
            </span>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="160">
          <template #default="{ row }">
            <span class="blue-action" @click="handleView(row)">查看</span>
            <span class="red-action" @click="handleDelete(row)">删除</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="page-box">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                       :page-sizes="[10,20,30,50]" background layout="total, sizes, prev, pager, next, jumper"
                       :total="tableData.length" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
    </div>

    <!-- 编辑/添加 弹窗 -->
    <el-dialog v-model="editDialogVisible" :title="dialogMode==='add'?'添加评估记录':'编辑评估记录'" width="620px">
      <el-form ref="editFormRef" :model="editForm" :rules="rules" label-width="120px">

        <!-- 姓名 -->
        <el-form-item label="姓名" prop="name" required>
          <el-input v-if="dialogMode==='add'" v-model="editForm.name" placeholder="请输入姓名"/>
          <span v-else>{{ editForm.name }}</span>
        </el-form-item>

        <!-- 账号 -->
        <el-form-item label="账号" prop="account" required>
          <el-input v-if="dialogMode==='add'" v-model="editForm.account" placeholder="请输入账号"/>
          <span v-else>{{ editForm.account }}</span>
        </el-form-item>

        <!-- 组织结构 -->
        <el-form-item label="组织结构" prop="org" required>
          <el-input v-if="dialogMode==='add'" v-model="editForm.org" placeholder="请输入组织结构"/>
          <span v-else>{{ editForm.org }}</span>
        </el-form-item>

        <!-- 评估人 -->
        <el-form-item label="评估人" prop="assessor" required>
          <el-input v-model="editForm.assessor" placeholder="请输入评估人"/>
        </el-form-item>

        <!-- 评估内容 -->
        <el-form-item label="评估内容" prop="content" required>
          <el-input type="textarea" v-model="editForm.content" :rows="3" placeholder="请输入评估内容"/>
        </el-form-item>

        <!-- 预警级别 -->
        <el-form-item label="预警级别" prop="warningLevel" required>
          <el-radio-group v-model="editForm.warningLevel">
            <el-radio label="high">高度预警</el-radio>
            <el-radio label="medium">中度预警</el-radio>
            <el-radio label="low">轻度预警</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 干预级别 -->
        <el-form-item label="干预级别" prop="interventionLevel" required>
          <el-radio-group v-model="editForm.interventionLevel">
            <el-radio label="care">高关怀</el-radio>
            <el-radio label="crisis">危机干预</el-radio>
            <el-radio label="normal">常规辅导</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 是否结案 -->
        <el-form-item label="是否结案" prop="isClosed">
          <el-switch v-model="editForm.isClosed" />
        </el-form-item>

        <!-- 上传文件 -->
        <el-form-item label="上传文件">
          <div class="upload-wrapper">
            <el-upload action="#" :before-upload="beforeUpload" :show-file-list="true" :limit="1">
              <el-button type="primary">选取文件</el-button>
            </el-upload>
            <div class="file-tip">
              只能上传 <span class="file-highlight">excel, word, ppt, zip</span> 文件，且 <span class="file-highlight">不超过2M</span>
            </div>
          </div>
        </el-form-item>

        <!-- 评估时间 -->
        <el-form-item label="评估时间" prop="assessTime" required>
          <el-date-picker v-model="editForm.assessTime" type="date" placeholder="选择日期"/>
        </el-form-item>

        <!-- 按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSaveEdit">{{ dialogMode==='add'?'立即创建':'保存修改' }}</el-button>
          <el-button class="reset-btn" @click="resetEditForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

const pageSize = ref(10)
const currentPage = ref(1)

const tableData = ref([
  { id: 1, assessTime: '2022-12-14', name: '李明', account: 'web9000', org: '博才学校，小学部，四年级，四一班', assessor: '张老师', lastUpdate: '2025-03-21 11:18' },
  { id: 2, assessTime: '2022-12-15', name: '张三', account: 'zhangsan', org: '实验小学，三年级，三二班', assessor: '李老师', lastUpdate: '2025-04-22 09:30' }
])
const tableDataCopy = ref([])
const currentPageTableData = ref([])

const sortField = ref('assessTime')
const sortOrder = ref('asc')

const filterOrg = ref('')
const filterName = ref('')
const filterAccount = ref('')
const filterAssessor = ref('')

const editDialogVisible = ref(false)
const dialogMode = ref('edit')

const editFormRef = ref(null)
const editForm = ref({
  id: null,
  name: '',
  account: '',
  org: '',
  assessor: '',
  content: '',
  warningLevel: '',
  interventionLevel: '',
  isClosed: false,
  file: null,
  assessTime: ''
})

const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  org: [{ required: true, message: '请输入组织结构', trigger: 'blur' }],
  assessor: [{ required: true, message: '请填写评估人', trigger: 'blur' }],
  content: [{ required: true, message: '请填写评估内容', trigger: 'blur' }],
  assessTime: [{ required: true, message: '请选择评估时间', trigger: 'change' }],
  warningLevel: [{ required: true, message: '请选择预警级别', trigger: 'change' }],
  interventionLevel: [{ required: true, message: '请选择干预级别', trigger: 'change' }]
}

const handleQuery = () => {
  const result = tableDataCopy.value.filter(item =>
      (!filterOrg.value || item.org.includes(filterOrg.value)) &&
      (!filterName.value || item.name.includes(filterName.value)) &&
      (!filterAccount.value || item.account.includes(filterAccount.value)) &&
      (!filterAssessor.value || item.assessor.includes(filterAssessor.value))
  )
  tableData.value = result
  handleCurrentChange(1)
}

const handleRefresh = () => {
  tableData.value = [...tableDataCopy.value]
  filterOrg.value = ''
  filterName.value = ''
  filterAccount.value = ''
  filterAssessor.value = ''
  handleCurrentChange(1)
}

const sortTable = prop => {
  if (sortField.value === prop) {
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortField.value = prop
    sortOrder.value = prop === 'lastUpdate' ? 'desc' : 'asc'
  }
  tableData.value.sort((a, b) => {
    let valA = a[prop], valB = b[prop]
    if (prop === 'assessTime' || prop === 'lastUpdate') {
      return sortOrder.value === 'asc' ? new Date(valA) - new Date(valB) : new Date(valB) - new Date(valA)
    }
    return sortOrder.value === 'asc'
        ? String(valA).localeCompare(String(valB))
        : String(valB).localeCompare(String(valA))
  })
  handleCurrentChange(currentPage.value)
}

const handleCurrentChange = newPage => {
  const start = (newPage - 1) * pageSize.value
  const end = start + pageSize.value
  currentPageTableData.value = tableData.value.slice(start, end)
}

const handleSizeChange = newPageSize => {
  pageSize.value = newPageSize
  currentPageTableData.value = tableData.value.slice(0, newPageSize)
  currentPage.value = 1
}

onMounted(() => {
  tableDataCopy.value = [...tableData.value]
  currentPageTableData.value = tableData.value.slice(0, pageSize.value)
})

const handleView = row => {
  dialogMode.value = 'edit'
  editForm.value = { ...row, file: null }
  editDialogVisible.value = true
}

const handleAdd = () => {
  dialogMode.value = 'add'
  editForm.value = { id: null, name: '', account: '', org: '', assessor: '', content: '', warningLevel: '', interventionLevel: '', isClosed: false, file: null, assessTime: '' }
  editDialogVisible.value = true
}

const beforeUpload = file => {
  const isAllowed = ['excel', 'word', 'presentation', 'zip'].some(ext => file.type.includes(ext))
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isAllowed) {
    ElMessage.error('只能上传 Excel / Word / PPT / Zip 文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传文件不能超过2MB!')
    return false
  }
  editForm.value.file = file
  return true
}

const handleSaveEdit = () => {
  if (dialogMode.value === 'add') {
    const newId = tableData.value.length ? Math.max(...tableData.value.map(d => d.id)) + 1 : 1
    const newRecord = {
      ...editForm.value,
      id: newId,
      lastUpdate: new Date().toISOString().slice(0, 16).replace('T', ' ')
    }
    tableData.value.push(newRecord)
    tableDataCopy.value = [...tableData.value]
    handleCurrentChange(currentPage.value)
    ElMessage.success('添加成功')
  } else {
    const idx = tableData.value.findIndex(item => item.id === editForm.value.id)
    if (idx !== -1) {
      tableData.value[idx] = { ...editForm.value, lastUpdate: new Date().toISOString().slice(0, 16).replace('T', ' ') }
      tableDataCopy.value = [...tableData.value]
      handleCurrentChange(currentPage.value)
      ElMessage.success('保存成功')
    }
  }
  editDialogVisible.value = false
}

const handleDelete = row => {
  tableData.value = tableData.value.filter(item => item.id !== row.id)
  tableDataCopy.value = [...tableData.value]
  handleCurrentChange(currentPage.value)
  ElMessage.success('删除成功')
}

const resetEditForm = () => {
  if (editFormRef.value) editFormRef.value.resetFields()
}
</script>

<style scoped>
.assess-list-container { padding: 20px; }
.action-bar { display: flex; align-items: flex-start; margin-bottom: 16px; }
.filters { display: flex; flex-wrap: wrap; margin-left: 20px; }
.filter-item { margin-right: 12px; width: 200px; }
.filter-actions { display: flex; align-items: center; margin-left: 12px; gap: 10px; }
.table-box { padding-left: 10px; }
.page-box { display: flex; justify-content: center; padding-left: 10px; margin-top: 10px; }
.sortable-header { cursor: pointer; user-select: none; display: inline-flex; align-items: center; gap: 4px; }
.sort-icons { display: flex; flex-direction: column; margin-left: 4px; line-height: 6px; }
.arrow { border: solid #ccc; border-width: 0 2px 2px 0; display: inline-block; padding: 3px; margin: 1px 0; transform: rotate(-135deg); transition: border-color 0.2s; }
.arrow.up { transform: rotate(-135deg); }
.arrow.down { transform: rotate(45deg); }
.arrow.active { border-color: #409EFF; }
.blue-action { color: #409EFF; margin-right: 12px; cursor: pointer; user-select: none; }
.red-action { color: #F56C6C; margin-right: 12px; cursor: pointer; user-select: none; }
.upload-wrapper { display: flex; flex-direction: column; position: relative; }
.file-tip { font-size: 12px; color: #666; margin-top: 4px; }
.file-tip .file-highlight { color: #F56C6C; font-weight: 600; }
.reset-btn { background: transparent; border: none; color: #606266; }
</style>
